package com.jxinternet.platform.services.service.impl.steps;

import com.jxinternet.platform.services.entity.domian.Log;
import com.jxinternet.platform.services.entity.domian.Message;
import com.jxinternet.platform.services.entity.domian.User;
import com.jxinternet.platform.services.entity.domian.Wealth;
import com.jxinternet.platform.services.entity.protobuf.LoginProtos.LoginRequest;
import com.jxinternet.platform.services.protocol.BaseProtocol;
import com.jxinternet.platform.services.protocol.Constants;
import com.jxinternet.platform.services.repository.convert.LogConvert;
import com.jxinternet.platform.services.repository.convert.UserConvert;
import com.jxinternet.platform.services.repository.convert.WealthContert;
import com.jxinternet.platform.services.repository.mysql.LogRepository;
import com.jxinternet.platform.services.repository.mysql.UserRepository;
import com.jxinternet.platform.services.repository.mysql.WealthRepository;
import com.jxinternet.platform.services.util.MD5Util;
import com.jxinternet.platform.services.util.SecurityUtil;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by gold-jx on 2017/6/26.
 * 登录分步骤
 */
@Slf4j
@Component
public class LoginSteps {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WealthRepository wealthRepository;

    @Autowired
    private LogRepository logRepository;

    @Autowired
    private UserConvert userConvert;

    @Autowired
    private WealthContert wealthContert;

    @Autowired
    private LogConvert logConvert;


    /**
     * step1
     * 验证请求
     */
    public Message step1_validateRequest(LoginRequest loginRequest) {
        Message message = new Message();
        try {
            //1.请求是否为空
            if (loginRequest == null) {
                message.setCode(BaseProtocol.Login_Request_Is_Null_Code);
                message.setRes(BaseProtocol.Login_Request_Is_Null_Res);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
            //2.用户名是否为空
            if ("".equals(loginRequest.getUserName()) || loginRequest.getUserName() == null) {
                message.setCode(BaseProtocol.Login_InvalidUsernameisNull_Code);
                message.setRes(BaseProtocol.Login_InvalidUsernameisNull_Des);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
            //3.用户密码是否为空
            if ("".equals(loginRequest.getPassword()) || loginRequest.getPassword() == null) {
                message.setCode(BaseProtocol.Login_InvalidPasswordisNull_Code);
                message.setRes(BaseProtocol.Login_InvalidasswordisNull_Des);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
        } catch (Exception e) {
            message.setCode(BaseProtocol.Login_Step01_Exception_Code);
            message.setRes(BaseProtocol.Login_Step01_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;
        }
        return message;
    }

    /**
     * step2
     * 验证用户
     */
    public Message step2_validateUser(String userName) {
        Message message = new Message();
        try {

            User user = userConvert.convertMysqlDomainToModel(userRepository.findByUserName(userName));
            if (user == null) {
                message.setCode(BaseProtocol.Login_InvalidUsernotExist_Code);
                message.setRes(BaseProtocol.Login_InvalidUsernotExist_Des);
                //log.error(message.getRes(), message.getCode());
                return message;
            }

            if (!Constants.STATE_NORMAL.equals(user.getState())) {
                message.setCode(BaseProtocol.Login_InvalidUsernotNormal_Code);
                message.setRes(BaseProtocol.Login_InvalidUsernotNormal_Des);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
            message.setData(user);
            return message;

        } catch (Exception e) {
            message.setCode(BaseProtocol.Login_Step02_Exception_Code);
            message.setRes(BaseProtocol.Login_Step02_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;
        }
    }


    /**
     * step3
     * 验证密码
     */
    public Message step3_validatePassword(User user, String password) {
        Message message = new Message();
        try {
            //1.取盐值
            String salt = user.getSalt();
            //2.盐值+密码是否等于旧密码
            String oldPassword = user.getPassword();
            String newPassword = MD5Util.getMD5to16(salt + password);
            if (!oldPassword.equals(newPassword)) {
                message.setCode(BaseProtocol.Login_InvalidPassword_Code);
                message.setRes(BaseProtocol.Login_Invalidassword_Des);
                //log.error(message.getRes(), message.getCode());
                return message;
            }

        } catch (Exception e) {
            message.setCode(BaseProtocol.Login_Step03_Exception_Code);
            message.setRes(BaseProtocol.Login_Step03_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;
        }
        return message;
    }

    /**
     * step4
     * 获取财富
     */
    public Message step4_validateWealth(String userName) {
        Message message = new Message();
        try {
            Wealth wealth =  wealthContert.convertMysqlDomainToModel(wealthRepository.findByUserName(userName));
            //如果wealth为空，初始化
            if (wealth == null) {
                wealth.setRechargePoint(Constants.WEALTH_INIT_GOLD_COUNT);
                wealth.setState(Constants.STATE_NORMAL);
                wealth.setPlatformNo(Constants.PLATFORM_NO);
                wealth.setUpdateTime(new Date());
                wealth.setCreateTime(new Date());
                wealth.setVersion(Constants.VERSION_INIT);
                wealthRepository.save(wealthContert.convertMysql(wealth));
            }

            if (wealth == null) {
                message.setCode(BaseProtocol.Login_Invalid_Wealth_Not_Exist_Code);
                message.setRes(BaseProtocol.Login_Invalid_Wealth_Not_Exist_Res);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
            if (!Constants.STATE_NORMAL.equals(wealth.getState())) {
                message.setCode(BaseProtocol.Login_Invalid_Wealth_Exception_Code);
                message.setRes(BaseProtocol.Login_Invalid_Wealth_Exception_Res);
                //log.error(message.getRes(), message.getCode());
                return message;
            }
        } catch (Exception e) {

            message.setCode(BaseProtocol.Login_Step04_Exception_Code);
            message.setRes(BaseProtocol.Login_Step04_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;

        }
        return message;
    }


    /**
     * step5
     * 创建token
     */
    public Message step5_createToken(String userName) throws Exception {
        Message message = new Message();
        try {
            String token = SecurityUtil.authentication(userName);
            message.setData(token);
        } catch (Exception e) {
            message.setCode(BaseProtocol.Login_Step05_Exception_Code);
            message.setRes(BaseProtocol.Login_Step05_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;
        }
        return message;

    }


    /**
     * step6
     * 保存日志
     */
    public Message step6_saveLog(String userName, String loginIp) throws Exception {
        Message message = new Message();
        try {
            Log log = new Log();
            log.setUserName(userName);
            log.setLoginIp(loginIp);
            log.setType(BaseProtocol.Area_Login);
            log.setOperation("登录");
            log.setState(Constants.STATE_NORMAL);
            log.setPlatformNo(Constants.PLATFORM_NO);
            log.setCreateTime(new Date());
            log.setUpdateTime(new Date());
            log.setVersion(Constants.VERSION_INIT);
            logRepository.save(logConvert.convertMysql(log));
        }catch (Exception e){
            message.setCode(BaseProtocol.Login_Step06_Exception_Code);
            message.setRes(BaseProtocol.Login_Step06_Exception_Res);
            //log.error(message.getRes(), message.getCode());
            return message;
        }
        return message;



    }


}
